/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package net.cjb.malacma.rssfeed.cron;

import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.cjb.malacma.rssfeed.googleapi.BloggerClient;

public final class TimerUtil extends TimerTask {


  /**
  * Construct and use a TimerTask and Timer.
  */
  public static void main (String... arguments ) {

    TimerTask fetchMail  = new TimerUtil();

    //perform the task once a day at 4 a.m., starting tomorrow morning
    //(other styles are possible as well)

    Timer timer = new Timer();
    timer.scheduleAtFixedRate(fetchMail, getTomorrowMorning4am(), fONCE_PER_DAY);
  }

  /**
  * Implements TimerTask's abstract run method.

  */
  public void run(){
        try {
            //toy implementation
            BloggerClient.createPost("pino.rss.feed", "daonde12345");
        } catch (ServiceException ex) {
            Logger.getLogger(TimerUtil.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TimerUtil.class.getName()).log(Level.SEVERE, null, ex);
        }

  }

  // PRIVATE ////

  //expressed in milliseconds
  private final static long fONCE_PER_DAY = 1000*24*60*60*60;


  private final static int fONE_DAY = 0;
  private final static int fFOUR_AM = 0;

  private final static int fZERO_MINUTES = 0;

  private static Date getTomorrowMorning4am(){

    Calendar tomorrow = new GregorianCalendar();
    tomorrow.add(Calendar.DATE, fONE_DAY);
    Calendar result = new GregorianCalendar(
      tomorrow.get(Calendar.YEAR),

      tomorrow.get(Calendar.MONTH),
      tomorrow.get(Calendar.DATE),
      fFOUR_AM,
      fZERO_MINUTES
    );
    return result.getTime();
  }
}
